<?php

namespace app\api\controller;

use addons\qrcode\controller\Index as quer;
use app\admin\model\card\Card;
use app\admin\model\gift\Gift;
use app\admin\model\teacher\Teacher;
use app\api\model\CollectionType;
use app\api\model\TradeBuy;
use app\api\model\TradeLog;
use app\api\model\TradeSell;
use app\api\model\Virtual;
use app\api\model\VirtualLog;
use app\common\controller\Api;
use app\common\model\User;

require(__DIR__ . '/../../../vendor/qiniu/php-sdk/autoload.php');

use Exception;
use Qiniu\Auth;
use Qiniu\Storage\UploadManager;
use think\Db;

class Trades extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    /**
     * 买单大厅列表(想买)
     *
     */
    public function buyList()
    {
        $token = $this->auth->getToken();
        if (!$token) {
            $data = $this->request->param();
            $pageSize = 5;
            $page = $data['page'] ?? 1; // 设置所需的页码
            $offset = ($page - 1) * $pageSize;
            $results = (new TradeBuy())->limit($offset, $pageSize)
                ->with('user')
                ->whereLike('user_mobile', "%{$data['user_mobile']}%")
                ->where('order_status', '>', 0)
                ->field('buy_order_id,user_id,user_mobile,order_ticket,least_deal_ticket,unit_price')
                ->order('buy_order_id', 'desc')
                ->select()->toArray();
            $count = (new TradeBuy())
                ->where('order_status', '>', 0)
                ->count();
            $this->success('成功', ['topMsg' => ['count' => $count, 'number' => 0], 'list' => $results]);
        }

        $uid = $this->getToken($token);
        $data = $this->request->param();
        $pageSize = 5;
        $page = $data['page'] ?? 1; // 设置所需的页码
        $offset = ($page - 1) * $pageSize;
        $results = (new TradeBuy())->limit($offset, $pageSize)
            ->with('user')
            ->whereLike('user_mobile', "%{$data['user_mobile']}%")
            ->where('order_status', '>', 0)
            ->field('buy_order_id,user_id,user_mobile,order_ticket,least_deal_ticket,unit_price')
            ->order('buy_order_id', 'desc')
            ->select()->toArray();
        $count = (new TradeBuy())
            ->where('order_status', '>', 0)
            ->count();
        $virtual = (new Virtual())->where(['user_id' => $uid])->field('virtual')->find();
        $this->success('成功', ['topMsg' => ['count' => $count, 'number' => $virtual['virtual']], 'list' => $results]);
    }

    /**
     * 卖单大厅列表(想卖)
     */
    public function sellList()
    {
        $token = $this->auth->getToken();
        if (!$token) {
            $data = $this->request->param();
            $pageSize = 5;
            $page = $data['page'] ?? 1; // 设置所需的页码
            $offset = ($page - 1) * $pageSize;
            $results = (new TradeSell())->limit($offset, $pageSize)
                ->with('user')
                ->whereLike('user_mobile', "%{$data['user_mobile']}%")
                ->where('order_status', '>', 0)
                ->field('sell_order_id,user_id,user_mobile,order_ticket,least_deal_ticket,unit_price')
                ->order('sell_order_id', 'desc')
                ->select()->toArray();
            $count = (new TradeSell())
                ->where('order_status', '>', 0)
                ->count();
            $this->success('成功', ['topMsg' => ['count' => $count, 'number' => 0], 'list' => $results]);
        }
        $uid = $this->getToken($token);
        $data = $this->request->param();
        $pageSize = 5;
        $page = $data['page'] ?? 1; // 设置所需的页码
        $offset = ($page - 1) * $pageSize;
        $results = (new TradeSell())->limit($offset, $pageSize)
            ->with('user')
            ->whereLike('user_mobile', "%{$data['user_mobile']}%")
            ->where('order_status', '>', 0)
            ->field('sell_order_id,user_id,user_mobile,order_ticket,least_deal_ticket,unit_price')
            ->order('sell_order_id', 'desc')
            ->select()->toArray();
        $count = (new TradeSell())
            ->where('order_status', '>', 0)
            ->count();
        $virtual = (new Virtual())->where(['user_id' => $uid])->field('virtual')->find();
        $this->success('成功', ['topMsg' => ['count' => $count, 'number' => $virtual['virtual']], 'list' => $results]);
    }

    /**
     * 发布求购信息
     * @ApiMethod (POST)
     */
    public function addBuy()
    {
        $token = $this->auth->getToken();
        $uid = $this->getToken($token);
        $buyData = $this->request->param();
        function is_within_business_hours()
        {
            $data1 = Db::table('fa_config')->where('id', 35)->field('id,value')->find();
            $data2 = Db::table('fa_config')->where('id', 36)->field('id,value')->find();
            // 获取当前时间的时间戳
            $currentTimestamp = time();

            // 转换为date对象，以便进行时间比较
            $currentTime = date('H:i', $currentTimestamp);

            // 定义业务开始和结束时间（24小时制）
            $startTime = $data1['value'];
            $endTime = $data2['value'];

            // 比较当前时间是否在指定范围内
            if ($currentTime >= $startTime && $currentTime <= $endTime) {
                return true; // 当前时间在业务时间内
            } else {
                return false; // 当前时间不在业务时间内
            }
        }

//         使用函数检查当前时间
        if (!is_within_business_hours()) {
            $this->error("请在交易时间内进行操作");
        }
        if (strpos($buyData['order_ticket'], '.')) {
            $this->error('只能购买整数');
        }
        //检测是否设置羽毛账户
        $virtual = new Virtual();
        $data = $virtual->where(['user_id' => $uid])->find();
        if (empty($data)) {
            $data1 = $virtual->create(['user_id' => $uid, 'virtual' => 0, 'remark' => '新注册', 'create_time' => date('Y-m-d H:i:s')]);
        }
        $data1 = Db::table('fa_config')->where('id', 32)->field('id,value')->find();
        $data2 = Db::table('fa_config')->where('id', 33)->field('id,value')->find();
        //判断交易单价
        if ($buyData['unit_price'] < $data1['value']) {
            $this->error('交易单价不能小于' . $data1['value']);
        } else if ($buyData['unit_price'] > $data2['value']) {
            $this->error('交易单价不能大于' . $data2['value']);
        }
        $userMobile = (new User())->where('id', $uid)->field('id,mobile')->find();
        $model = new TradeBuy();
        $model->addBuys($uid, $userMobile['mobile'], $buyData['order_ticket'],
            $buyData['least_deal_ticket'], $buyData['unit_price'], '求购');
        $this->success('发布成功');
    }

    /**
     * 发布售出信息
     * @ApiMethod (POST)
     */
    public function addSell()
    {
        $token = $this->auth->getToken();
        $uid = $this->getToken($token);
        $this->error('暂未开放');
        $sellData = $this->request->param();
        function is_within_business_hours()
        {
            $data1 = Db::table('fa_config')->where('id', 35)->field('id,value')->find();
            $data2 = Db::table('fa_config')->where('id', 36)->field('id,value')->find();
            // 获取当前时间的时间戳
            $currentTimestamp = time();

            // 转换为date对象，以便进行时间比较
            $currentTime = date('H:i', $currentTimestamp);

            // 定义业务开始和结束时间（24小时制）
            $startTime = $data1['value'];
            $endTime = $data2['value'];

            // 比较当前时间是否在指定范围内
            if ($currentTime >= $startTime && $currentTime <= $endTime) {
                return true; // 当前时间在业务时间内
            } else {
                return false; // 当前时间不在业务时间内
            }
        }

//         使用函数检查当前时间
        if (!is_within_business_hours()) {
            $this->error("请在交易时间内进行操作");
        }
        //检测是否设置羽毛账户
        $virtual = new Virtual();
        $VirtualLogModel = new VirtualLog();
        $data = $virtual->where(['user_id' => $uid])->find();
        if (empty($data)) {
            $data1 = $virtual->create(['user_id' => $uid, 'virtual' => 0, 'remark' => '新注册', 'create_time' => date('Y-m-d H:i:s')]);
        }
        $data1 = Db::table('fa_config')->where('id', 32)->field('id,value')->find();
        $data2 = Db::table('fa_config')->where('id', 33)->field('id,value')->find();
        //判断交易单价
        if ($sellData['unit_price'] < $data1['value']) {
            $this->error('交易单价不能小于' . $data1['value']);
        } else if ($sellData['unit_price'] > $data2['value']) {
            $this->error('交易单价不能大于' . $data2['value']);
        }
        //只能发布整数
        if (strpos($sellData['order_ticket'], '.')) {
            $this->error('只能售出整数');
        }
        $virtualMoney = new Virtual();
        $userInfo = (new User())->where('id', $uid)->field('id,mobile,pay_pass')->find();
        $virtual = $virtualMoney->where(['user_id' => $uid])->field('virtual')->find();
        //验证羽毛
        if ($virtual['virtual'] < $sellData['order_ticket']) {
            $this->error('羽毛不足');
        }
        $model = new TradeSell();
        try {
            //更新用户羽毛
            $virtualMoney->updateMoney1($uid, $sellData['order_ticket'], '售出扣除');
            $model->addSells($uid, $userInfo['mobile'], $sellData['order_ticket'],
                $sellData['least_deal_ticket'], $sellData['unit_price'], '售出');
            $VirtualLogModel->addLog($uid, '羽毛-售出', '-' . $sellData['order_ticket']);
        } catch (\Exception $e) {
            $this->error($e->getMessage());
        }
        $this->success('发布成功');
    }

    /**
     * 发起转赠
     * @ApiMethod (POST)
     */
    public function Transfer()
    {
        $token = $this->auth->getToken();
        $uid = $this->getToken($token);
        $transferData = $this->request->param();
        $buy_order_id = $this->request->post('buy_order_id', 0);
        $userMobile = (new User())->where('id', $uid)->field('id,mobile,pay_pass')->find();
        $virtual = (new Virtual())->where(['user_id' => $uid])->field('virtual')->find();
        $model = new TradeLog();
        $VirtualLogModel = new VirtualLog();
        $tradeBuyModel = new TradeBuy();
        $collection = new CollectionType();
        $buyData = $tradeBuyModel->where(['buy_order_id' => $buy_order_id])->field('user_id,unit_price,order_ticket')->find();
        if ($buyData['order_ticket'] < $transferData['deal_ticket']) {
            $this->error('已经卖光了哦~');
        }
        $collectionData = $collection->where(['user_id' => $uid])->field('collection_id')->find();
        if ($collectionData == null) {
            $this->error('请先设置收款信息!');
        }
        if ($transferData['deal_ticket'] == 0) {
            $this->error('不能赠送0个!');
        }
        if (strpos($transferData['deal_ticket'], '.')) {
            $this->error('只能售出整数');
        }
        $dealMoney = $buyData['unit_price'] * $transferData['deal_ticket'];
        $VirtualModel = new Virtual();
        //查询交易时间
        function is_within_business_hours()
        {
            $data1 = Db::table('fa_config')->where('id', 35)->field('id,value')->find();
            $data2 = Db::table('fa_config')->where('id', 36)->field('id,value')->find();
            // 获取当前时间的时间戳
            $currentTimestamp = time();

            // 转换为date对象，以便进行时间比较
            $currentTime = date('H:i', $currentTimestamp);

            // 定义业务开始和结束时间（24小时制）
            $startTime = $data1['value'];
            $endTime = $data2['value'];

            // 比较当前时间是否在指定范围内
            if ($currentTime >= $startTime && $currentTime <= $endTime) {
                return true; // 当前时间在业务时间内
            } else {
                return false; // 当前时间不在业务时间内
            }
        }

        // 使用函数检查当前时间
        if (!is_within_business_hours()) {
            $this->error("请在交易时间内进行操作");
        }
        //验证羽毛
        if ($virtual['virtual'] < $transferData['deal_ticket']) {
            $this->error('羽毛不足');
        }
        try {
            //扣除羽毛
            $VirtualModel->updateMoney1($uid, $transferData['deal_ticket'], '羽毛-转赠' . $transferData['deal_ticket']);
            //更新订单羽毛字段
            $tradeBuyModel->updateTicket1($buy_order_id, $transferData['deal_ticket'], $userMobile['mobile'], $userMobile['mobile'] . '转赠');
//            $VirtualModel->updateMoney2($buyData['user_id'], $transferData['deal_ticket'], '羽毛-获赠' . $transferData['deal_ticket']);
            //订单信息
            $model->addTransfer1($buy_order_id, $uid, $buyData['user_id'], $userMobile['mobile'], $transferData['order_type'], $transferData['deal_ticket'], $dealMoney, '转赠');
            //扣除羽毛记录
            $VirtualLogModel->addLog($uid, '羽毛-转赠', '-' . $transferData['deal_ticket']);
            if (intval($transferData['deal_ticket']) == intval($buyData['order_ticket'])) {
                $tradeBuyModel->where(['buy_order_id' => $buy_order_id])->update(['order_status' => 0]);
            }
        } catch (\Exception $e) {
            $this->error('转赠失败', $e->getMessage());
        }
        $this->success('转增成功！');
    }

    /**
     *获取今日羽毛总和
     */
    public function getVirtual()
    {
        $virtual = (new Virtual())->field('virtual')->select()->toArray();
        $virtualCount = null;
        foreach ($virtual as $key => $value) {
            $virtualCount += $value['virtual'];
        }
        $this->success('success', $virtualCount);
    }

    /**
     * 设置原始密码
     */
    public function setPayPass()
    {
        $data = User::field('id,mobile,pay_pass')->select()->toArray();
        foreach ($data as $key => $value) {
            if (empty($value['pay_pass'])) {
                User::where(['id' => $value['id']])->update(['pay_pass' => 123456 . substr($value['mobile'], -5)]);
            }
        }
        $this->success('', $data);
    }

    /**
     * 发起买入
     * @ApiMethod (POST)
     */
    public function buyVirtual()
    {
        $token = $this->auth->getToken();
        $uid = $this->getToken($token);
        $this->error('暂未开放');
        $transferData = $this->request->param();
        $sell_order_id = $this->request->post('sell_order_id', 0);
//        halt(empty($transferData['pay_voucher']) ? 2 : 1);
        function is_within_business_hours()
        {
            $data1 = Db::table('fa_config')->where('id', 35)->field('id,value')->find();
            $data2 = Db::table('fa_config')->where('id', 36)->field('id,value')->find();
            // 获取当前时间的时间戳
            $currentTimestamp = time();

            // 转换为date对象，以便进行时间比较
            $currentTime = date('H:i', $currentTimestamp);

            // 定义业务开始和结束时间（24小时制）
            $startTime = $data1['value'];
            $endTime = $data2['value'];

            // 比较当前时间是否在指定范围内
            if ($currentTime >= $startTime && $currentTime <= $endTime) {
                return true; // 当前时间在业务时间内
            } else {
                return false; // 当前时间不在业务时间内
            }
        }
//         使用函数检查当前时间
        if (!is_within_business_hours()) {
            $this->error("请在交易时间内进行操作");
        }
        if (strpos($transferData['deal_ticket'], '.')) {
            $this->error('只能售出整数');
        }
        $userMobile = (new User())->where('id', $uid)->field('id,mobile')->find();
        $model = new TradeLog();
        $tradeSellModel = new TradeSell();
        $buyData = $tradeSellModel->where(['sell_order_id' => $sell_order_id])->field('user_id,unit_price,order_ticket')->find();
        if ($buyData['order_ticket'] < $transferData['deal_ticket']) {
            $this->error('已经卖光了哦~');
        }
        $collection = new CollectionType();
        $collectionData = $collection->where(['user_id' => $uid])->field('collection_id')->find();
        if ($collectionData == null) {
            $this->error('请先设置收款信息!');
        }

        //判断金额还有多少
        //计算价格
        $dealMoney = $buyData['unit_price'] * $transferData['deal_ticket'];
        $orderData = [];
        try {
            $orderData = $model->addTransfer2($sell_order_id, $uid, $buyData['user_id'], $transferData['pay_voucher'], $userMobile['mobile'], $transferData['order_type'], $transferData['deal_ticket'], $dealMoney, '买入');
            //更新订单羽毛字段
            $tradeSellModel->updateTicket2($sell_order_id, $transferData['deal_ticket'], $userMobile['mobile'], $userMobile['mobile'] . '买入');
            if (intval($transferData['deal_ticket']) == intval($buyData['order_ticket'])) {
                $tradeSellModel->where(['sell_order_id' => $sell_order_id])->update(['order_status' => 0]);
            }
        } catch (\Exception $e) {
            $this->error('购买失败', $e->getMessage());
        }
        $this->success('购买成功!', $orderData);
    }

    /**
     *批量实名
     */
    public function uploadReal()
    {
        $file = $_FILES['file'];
        $data = $this->uploadImg($file);
        $fileLines = file($data, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
        $dataArray = array_map('trim', $fileLines);
        foreach ($dataArray as $key => $value) {
            User::where(['mobile' => $value])->update(['username' => '已实名', 'id_card' => 370811199001060951, 'facePhotoUrl' => 'https://hyxs.ychlkj.cn/uploads/20240126/e43e70a1d9648ab4d2421b929a9ebe17.jpg']);
        }
        $this->success('处理成功!');
    }

    /**
     *上传文件
     */
    public function uploadImg()
    {
        //获取文件后缀名
        $file = $_FILES['file'];
        $extension = substr($file['name'], strrpos($file['name'], '.') + 1);
        $path = $file['tmp_name'];
//        halt($extension);
        // 需要填写你的 Access Key 和 Secret Key
        $accessKey = "JJq1CXA9ZY2BjxjhmLyMC-7en1vxZuVSjoypJFh2";
        $secretKey = "lEwJKFPDgwxvxel2BhJkH6v6WP2Nqxy1bW4jyQ8n";
        $bucket = "hhwy584";
        // 构建鉴权对象
        $auth = new Auth($accessKey, $secretKey);
        // 生成上传 Token
        $token = $auth->uploadToken($bucket);
        // 要上传文件的本地路径
        $filePath = $path;
        // 上传到存储后保存的文件名
        $key = uniqid() . time() . '.' . $extension;
        // 初始化 UploadManager 对象并进行文件的上传。
        $uploadMgr = new UploadManager();
        // 调用 UploadManager 的  putFile 方法进行文件的上传。
        list($ret, $err) = $uploadMgr->putFile
        ($token, $key, $filePath, null, 'application/octet-stream', true, null, 'v2');
        $data = 'http://qiniu.hhwyxs.cn/' . $key;
        return $data;
    }

    /**
     * 获取订单（买的）
     */
    public function getOrderBuy()
    {
        $token = $this->auth->getToken();
        $uid = $this->getToken($token);
        $tradeLogModel = new TradeLog();
        $tradeSellModel = new TradeBuy();
        $data = $this->request->param();
        $pageSize = 5;
        $page = $data['page'] ?? 1; // 设置所需的页码
        $offset = ($page - 1) * $pageSize;
        $buyData = $tradeLogModel->where(['buy_user_id' => $uid])
            ->limit($offset, $pageSize)
            ->where('buy_deal_status', '>', 0)
            ->where('sell_deal_status', '>', 0)
            ->field('buy_log_id,sell_order_id,buy_order_id,sell_user_id,deal_ticket,
        deal_money,order_number,buy_deal_status,sell_deal_status,create_time,effective_end_time')
            ->orderRaw("FIELD(buy_deal_status, 2) DESC, FIELD(buy_deal_status, 1) DESC, FIELD(buy_deal_status, 3) DESC, create_time DESC")
            ->select()
            ->toArray();
        $buyDataCount = $tradeLogModel->where(['buy_user_id' => $uid,])
            ->where('buy_deal_status', '>', 0)
            ->where('sell_deal_status', '>', 0)
            ->count();
//        halt($buyDataCount);
        $sellUserId = [];
        $sellUserInfo = [];
        foreach ($buyData as $key => $value) {
            //查我买的谁的
            $sellUserId[] = User::where(['id' => $value['sell_user_id']])->field('id,nickname,mobile,username')->find();
            $buyData[$key]['unit_price'] = $value['deal_money'] / $value['deal_ticket'];
            $buyData[$key]['buy_deal_status'] = ($value['buy_deal_status'] == 1) ? '待审核' : (($value['buy_deal_status'] == 2) ? '待付款' : (($value['buy_deal_status'] == 3) ? '已完成' : (($value['buy_deal_status'] == 4) ? '已超时' : '')));
        }
        foreach ($sellUserId as $key => $value) {
            $buyData[$key]['user'][] = $value['id'];
            $buyData[$key]['user'][] = $value['nickname'];
            $buyData[$key]['user'][] = $value['mobile'];
            $buyData[$key]['user'][] = $value['username'];
        }
        $this->success('', ['count' => $buyDataCount, 'list' => $buyData]);
    }

    /**
     * 处理付款超时（未付款）
     */
    public function Timeout()
    {
        //获取所有未付款订单
        $noPayment = new TradeLog();
        $buyModel = new TradeBuy();
        $sellModel = new TradeSell();
        $virtual = new Virtual();
        $virtualLog = new VirtualLog();
        $data = $noPayment->where('buy_deal_status', 2)->select()->toArray();
        $buyList = [];
        $sellList = [];
        foreach ($data as $key => $value) {
            if ($value['order_type'] == 1) { //主动买的
                $buyList[] = $value;
            } else if ($value['order_type'] == 2) {//别人卖的
                $sellList[] = $value;
            }
        }
        $outBuyTime = [];
        $outSellTime = [];
        //筛选出超时的订单(买的)
        foreach ($buyList as $key => $value) {
            if (time() > strtotime($value['effective_end_time'])) {
                $outBuyTime[] = $value;
            }
        }
        //筛选出超时的订单（卖的）
        foreach ($sellList as $key => $value) {
            if (time() > strtotime($value['effective_end_time'])) {
                $outSellTime[] = $value;
            }
        }
//        $this->success('', ['买的超时'=>$outBuyTime, '卖的超时'=>$outSellTime]);
//        开始处理超时逻辑(买的)
        if (!empty($outBuyTime)) {
            foreach ($outBuyTime as $key => $value) {
                //修改订单状态为已超时
                $noPayment->where(['buy_log_id' => $value['buy_log_id']])->update(['buy_deal_status' => 0, 'sell_deal_status' => 0]);
                //退还卖单余额
//                if ($value['order_status'] == 0) {
                $sellModel->where(['sell_order_id' => $value['sell_order_id'], 'order_status' => 0])->update(['order_status' => 1]);
//                }
                $sellModel->updateTicket3($value['sell_order_id'], $value['deal_ticket'], $value['user_mobile'], $value['user_mobile'] . '' . '未付款超时退还');
            }
        }
//        //开始处理超时逻辑（卖的）
        if (!empty($outSellTime)) {
            foreach ($outSellTime as $key => $value) {
                //退还买单余额
//                if ($value['order_status'] === 0) {
                $buyModel->where(['buy_order_id' => $value['buy_order_id'], 'order_status' => 1])->update(['order_status' => 1]);
//                }
                $noPayment->where(['buy_log_id' => $value['buy_log_id']])->update(['buy_deal_status' => 0, 'sell_deal_status' => 0]);
                $buyModel->updateTicket4($value['buy_order_id'], $value['deal_ticket'], $value['user_mobile'], $value['user_mobile'] . '' . '未付款超时退还');
                //退还卖家余额
                $virtual->updateMoney2($value['sell_user_id'], $value['deal_ticket'], $value['user_mobile'] . '' . '买家未付款超时退还');
                $virtualLog->addLog($value['sell_user_id'], '买家未付款超时退款', '+' . $value['deal_ticket']);
            }
        }
        $this->success('', ['买的超时' => $outBuyTime, '卖的超时' => $outSellTime]);
    }

    /**
     * 获取订单（卖的）
     */
    public function getOrderSell()
    {
        $token = $this->auth->getToken();
        $uid = $this->getToken($token);
        $tradeLogModel = new TradeLog();
        $tradeSellModel = new TradeSell();
        $data = $this->request->param();
        $pageSize = 5;
        $page = $data['page'] ?? 1; // 设置所需的页码
        $offset = ($page - 1) * $pageSize;
        $buyData = $tradeLogModel->where(['sell_user_id' => $uid])
            ->limit($offset, $pageSize)
            ->where('buy_deal_status', '>', 0)
            ->where('sell_deal_status', '>', 0)
            ->field('buy_log_id,buy_order_id,buy_user_id,deal_ticket,
            pay_voucher,deal_money,order_number,sell_deal_status,buy_deal_status,create_time,effective_end_time')
            ->orderRaw("FIELD(sell_deal_status, 1) DESC, FIELD(sell_deal_status, 2) DESC, create_time DESC")
            ->select()
            ->toArray();
        $buyDataCount = $tradeLogModel->where(['sell_user_id' => $uid])
            ->limit($offset, $pageSize)
            ->where('buy_deal_status', '>', 0)
            ->where('sell_deal_status', '>', 0)
            ->field('buy_log_id,buy_order_id,buy_user_id,deal_ticket,
            pay_voucher,deal_money,order_number,sell_deal_status,buy_deal_status,create_time,effective_end_time')
            ->count();
//        $this->success('', $buyDataCount);
        $sellUserId = [];
        $sellUserInfo = [];
        foreach ($buyData as $key => $value) {
            //查我卖的谁
            $sellUserId[] = User::where(['id' => $value['buy_user_id']])->field('id,nickname,mobile,username')->find();
            $buyData[$key]['unit_price'] = $value['deal_money'] / $value['deal_ticket'];
            $buyData[$key]['sell_deal_status'] = ($value['sell_deal_status'] == 1) ? '待放行' : (($value['sell_deal_status'] == 2) ? '已完成' : (($value['sell_deal_status'] == 3) ? '已超时' : ''));
        }
        foreach ($sellUserId as $key => $value) {
            $buyData[$key]['user'][] = $value['id'];
            $buyData[$key]['user'][] = $value['nickname'];
            $buyData[$key]['user'][] = $value['mobile'];
            $buyData[$key]['user'][] = $value['username'];
        }
        $this->success('', ['count' => $buyDataCount, 'list' => $buyData]);
    }

    /**
     * 购买支付（给转赠人支付）
     */
    public function buyPay()
    {
        $token = $this->auth->getToken();
        $uid = $this->getToken($token);
        $data = $this->request->param();
        $modelBuyLog = new TradeLog();
        $endTime = $modelBuyLog->where(['buy_log_id' => $data['buy_log_id']])->field('buy_log_id,buy_deal_status,effective_end_time')->find();
//        $this->success('', $endTime);
        //订单结束三分钟前禁止交易
//        if (time() > strtotime($endTime['effective_end_time']) - 180) {
//            $this->error('订单即将结束,禁止交易！');
//        }
//        $this->success('',$endTime);
        $modelBuyLog->updateImg1($data['buy_log_id'], $data['pay_voucher']);
        $modelBuyLog->where(['buy_log_id' => $data['buy_log_id']])->update(['buy_deal_status' => 1]);
        $this->success('付款成功!');
    }

    /**
     * 确认放行
     */
    public function getSellImg()
    {
        $token = $this->auth->getToken();
        $uid = $this->getToken($token);
        $data = $this->request->post();
        $modelBuyLog = new TradeLog();
        $VirtualModel = new Virtual();
        $VirtualLogModel = new VirtualLog();
        $buyMoney = $modelBuyLog->where(['buy_log_id' => $data['buy_log_id']])->field('buy_user_id,deal_ticket,sell_deaL_status')->find();
//        if ($modelBuyLog['sell_deal_status'] == 3) {
//            $this->error('买家未付款已超时！');
//        }
        try {
            $modelBuyLog->where(['buy_log_id' => $data['buy_log_id']])->update(['sell_deal_status' => 2]);
            $modelBuyLog->where(['buy_log_id' => $data['buy_log_id']])->update(['buy_deal_status' => 3]);
            $VirtualModel->updateMoney2($buyMoney['buy_user_id'], $buyMoney['deal_ticket'], '羽毛-获赠' . $buyMoney['deal_ticket']);
            $VirtualLogModel->addLog($buyMoney['buy_user_id'], '羽毛-获赠', '+' . $buyMoney['deal_ticket']);
        } catch (\Exception $e) {
            $this->error('放行失败');
        }
        $this->success('放行成功');
    }

    /**
     * 获取我的体现方式信息
     */
    public function getPay()
    {
        $token = $this->auth->getToken();
        $uid = $this->getToken($token);
        $payType = new CollectionType();
        $userPayInfo = $payType->where(['user_id' => $uid])
            ->field('collection_id,user_id,real_name,collection_mobile,wechat_qrcode,alipay_qrcode,card_number')->find();
        if ($userPayInfo) {
            $this->success('获取成功', $userPayInfo);
        } else {
            $this->success('请设置收款方式');
        }
    }

    /**
     * 获取订单体现方式信息
     */
    public function getOrderPay()
    {
        $payType = new CollectionType();
        $payBuy = new TradeBuy();
        $paySell = new TradeSell();
        $TradeLog = new TradeLog();
        $payBuyInfo = $this->request->post('buy_order_id');
        $paySellInfo = $this->request->post('sell_order_id');
        $mobile = $this->request->post('mobile');
        if (empty($paySellInfo)) {
            $sellId = $TradeLog->where(['buy_order_id' => $payBuyInfo, "user_mobile" => $mobile])->field('sell_user_id,user_mobile')->find();
            $userPayInfo = $payType->where(['user_id' => $sellId['sell_user_id']])
                ->field('collection_id,user_id,real_name,collection_mobile,wechat_qrcode,alipay_qrcode,card_number')->find();
            $this->success('获取成功', $userPayInfo);
        } else if (empty($payBuyInfo)) {
            $buyId = $paySell->where('sell_order_id', $paySellInfo)->field('user_id')->find();
//            $this->success('',$buyId);
            $userPayInfo = $payType->where(['user_id' => $buyId['user_id']])
                ->field('collection_id,user_id,real_name,collection_mobile,wechat_qrcode,alipay_qrcode,card_number')->find();
            $this->success('获取成功', $userPayInfo);
        }
    }

    /**
     * 设置体现方式
     */
    public function setPay()
    {
        $token = $this->auth->getToken();
        $uid = $this->getToken($token);
        $payType = new CollectionType();
        $userPayInfo = $payType->where(['user_id' => $uid])->withField('collection_email,create_by,create_time,update_by,update_time,remark')->find();
        $payData = $this->request->param();
//        $wechat = $_FILES['wechat_qrcode'];
//        $alipay = $_FILES['alipay_qrcode'];
        try {
//            $payWechat = $this->uploadImg($wechat);
//            $payAlipay = $this->uploadImg($alipay);
            if (empty($userPayInfo)) {
                $payType->addCollection($uid, $payData['name'], $payData['mobile'], $payData['wechat_qrcode'], $payData['card_number'], $payData['alipay_qrcode'], '设置收款方式');
            } else {
                $payType->updataCollection($uid, $payData['name'], $payData['mobile'], $payData['wechat_qrcode'], $payData['card_number'], $payData['alipay_qrcode'], '更新收款方式');
            }
        } catch (\Exception $e) {
            $this->error('保存失败！', $e->getMessage());
        }
        $this->success('保存成功!');
    }

    /**
     *监听订单执行时间
     */
    public function listenOrder()
    {
        $modelBuyLog = new TradeLog();
        $VirtualModel = new Virtual();
        $tradeSellModel = new TradeSell();
        $tradeBuyModel = new TradeBuy();
        //查询所有卖单订单
        $buyLog = $modelBuyLog
            ->field('buy_log_id,buy_order_id,sell_order_id,buy_user_id,sell_user_id,
            order_type,deal_ticket,buy_deal_status,sell_deal_status,effective_end_time')
            ->select()
            ->toArray();
        foreach ($buyLog as $key => $value) {
            if ($value['order_type'] == 1) {
                $type1[] = $value;//卖单
            } else if ($value['order_type'] == 2) {
                $type2[] = $value;//买单
            }
        }
        $this->success('', $type1);
    }

    /**
     *获取我的羽毛
     */
    public function getMyVirtual()
    {
        $token = $this->auth->getToken();
        $uid = $this->getToken($token);
        $VirtualModel = new Virtual();
        $VirtualInfo = $VirtualModel->where(['user_id' => $uid])->field('virtual')->find();
        $this->success('获取成功', $VirtualInfo['virtual']);
    }

    /**
     * 羽毛转换
     */
    public function virtual()
    {
        $token = $this->auth->getToken();
        $uid = $this->getToken($token);
//        $this->error('暂未开放');
        $money = $this->request->post('money');
        //检测是否设置羽毛账户
        $virtual = new Virtual();
        $data = $virtual->where(['user_id' => $uid])->find();
        if (empty($data)) {
            $data1 = $virtual->create(['user_id' => $uid, 'virtual' => 0, 'remark' => '新注册', 'create_time' => date('Y-m-d H:i:s')]);
        }
        $Fee = $this->getShareFee($uid);
        $a = $Fee / 100;
        $moneyFinal = $money / (1 - $a);
        //分红金额
        $bonus = $moneyFinal - $money;
        $userMoney = User::Where('id', $uid)->field('id,money')->find();
        $userCard = Db::table('fa_view_card_user')
            ->where(['user_id' => $uid])->count();
        if ($userCard < 3) {
            $this->error('请先持有2个观阅包！');
        }
//        $this->success('', $userCard);
        if ($moneyFinal > $userMoney['money']) {
            $this->error('书券不足');
        }
        //只能兑换整数
//        if (strpos($money, '.')) {
//            $this->error('只能兑换整数');
//        }
        $virtual = new Virtual();
        $virtualLog = new VirtualLog();
        Db::startTrans();
        try {
            $virtual->updateMoney2($uid, $money, '书券兑换羽毛');
            $virtualLog->addLog($uid, '羽毛-兑换', '+' . $money);
            User::money(-$moneyFinal, $uid, '书券兑换羽毛扣除');
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->error('兑换失败');
        }
        $this->success('成功');
    }

    /**
     * 发起撤单
     */
    public function cancel()
    {
        $token = $this->auth->getToken();
        $uid = $this->getToken($token);
        $buyId = $this->request->post('buy_order_id');
        $sellId = $this->request->post('sell_order_id');
        $buy = new TradeBuy();
        $sell = new TradeSell();
        $orderLog = new TradeLog();
        $virtualMoney = new Virtual();
        $VirtualLog = new VirtualLog();
        if (!empty($buyId)) {
            //查询买单信息
            $buyData = $buy->where('buy_order_id', $buyId)->find();
//            $this->success('',$buyData);
            if ($buyData['order_status'] == -1) {
                $this->error('已经撤单了');
            }
            //查询订单信息
            $orderBuyData = $orderLog->where(['buy_order_id' => $buyId, 'buy_deal_status' => 2])->select()->toArray();
//            $this->success('',$orderLogData);
            //如果自己未付款,给转赠人退款
            foreach ($orderBuyData as $key => $value) {
                $orderLog->where('buy_log_id', $value['buy_log_id'])->update(['buy_deal_status' => 0, 'sell_deal_status' => 0]);
                $virtualMoney->updateMoney2($value['sell_user_id'], $value['deal_ticket'], '卖单退款');
                $VirtualLog->addLog($value['sell_user_id'], '卖单退款', '+' . $value['deal_ticket']);
            }
            $buy->where('buy_order_id', $buyId)->update(['order_status' => -1]);
            $this->success('撤单成功');
        } else if (!empty($sellId)) {
            //查询卖单信息
            $sellData = $sell->where('sell_order_id', $sellId)->find();
            if ($sellData['order_status'] == -1) {
                $this->error('已经撤单了');
            }
            $orderSellData = $orderLog->where(['sell_order_id' => $sellId, 'buy_deal_status' => 2])->select()->toArray();
            //如果买家未付款,给自己退款（先退订单）
            $virtualMoney->updateMoney2($uid, $sellData['order_ticket'], '撤单用户未支付退款');
            $VirtualLog->addLog($uid, '卖单退款', '+' . $sellData['order_ticket']);
            foreach ($orderSellData as $key => $value) {
                //隐藏订单
                $orderLog->where('buy_log_id', $value['buy_log_id'])->update(['buy_deal_status' => 0, 'sell_deal_status' => 0]);
                //退还用户未支付的金额
                $virtualMoney->updateMoney2($uid, $value['deal_ticket'], '撤单用户未支付退款');
                $VirtualLog->addLog($uid, '卖单退款', '+' . $value['deal_ticket']);
            }
            $sell->where('sell_order_id', $sellId)->update(['order_status' => -1]);
            $this->success('撤单成功');
        }
    }

    /**
     * 书券转换
     */
    public function share()
    {
        $token = $this->auth->getToken();
        $uid = $this->getToken($token);
        $money = $this->request->post('money');
        $virtual = new Virtual();
        $virtualLog = new VirtualLog();
        $VirtualInfo = $virtual->where(['user_id' => $uid])->field('virtual')->find();
        if ($money > $VirtualInfo['virtual']) {
            $this->error('羽毛不足');
        }
        $virtual->updateMoney1($uid, $money, '羽毛兑换扣除书券');
        $virtualLog->addLog($uid, '书券-兑换', '-' . $money);
        User::money(+$money, $uid, '用户羽毛兑换书券获得');
        $this->success('', $money);
    }

    //获取今日参考价
    public function getShareFeeToday()
    {
        $data1 = Db::table('fa_config')->where('id', 32)->field('id,value')->find();
        $data2 = Db::table('fa_config')->where('id', 33)->field('id,value')->find();
        $this->success('', ["minMoney" => $data1['value'], "maxMoney" => $data2['value']]);
    }

    /**
     * 获取交易时间
     * */
    public function getTradeTime()
    {
        $data1 = Db::table('fa_config')->where('id', 35)->field('id,value')->find();
        $data2 = Db::table('fa_config')->where('id', 36)->field('id,value')->find();
        $this->success('', '每日交易时间：' . $data1['value'] . '-' . $data2['value'] . "(请在期间内完成交易)");
    }

    /**
     *获取羽毛明细
     */
    public function getVirtualLog()
    {
        $token = $this->auth->getToken();
        $uid = $this->getToken($token);
        $virtualLog = new VirtualLog();
        $log = $virtualLog->where(['user_id' => $uid])
            ->field('id,user_id,remark,value,create_time')
            ->order('create_time', 'desc')
            ->select()->toArray();
        $this->success('', $log);
    }

    /**
     * 创建羽毛表
     */
    public function createVirtual()
    {
        $token = $this->auth->getToken();
        $uid = $this->getToken($token);
//        $this->success('', $uid);
        $virtual = new Virtual();
        $data = $virtual->where(['user_id' => $uid])->find();
        if (empty($data)) {
            $data1 = $virtual->create(['user_id' => $uid, 'virtual' => 0, 'remark' => '新注册', 'create_time' => date('Y-m-d H:i:s')]);
        }
        $this->success('创建成功');
    }

    public function getShareFee($uid)
    {
        $gift = new Gift();
        //我的直推人数
        $userCount = (new User())->where(['pid' => $uid])->field('id')->count();
        //规则
        $giftRules = (new Gift())->field('id,criteria,value')->select()->toArray();
        // 根据直推人数找到符合条件的奖励
        $datacriteria = array_column($giftRules, 'criteria');
        $datavalue = array_column($giftRules, 'value');
//        halt($count);
        $deductMoney = null;
        if ($userCount <= $datacriteria[0]) {
            //扣除的书券
            $deductMoney = $datavalue[0];
        }
        if ($userCount >= 4) {
            foreach ($datacriteria as $index => $criteria) {
                if ($userCount < $criteria) {
                    //扣除的书券
                    $deductMoney = $datavalue[$index - 1];
                    break;
                }
            }
        }
//        halt($deductMoney);
        if (end($datacriteria) <= $userCount) {
            //扣除的书券
            $deductMoney = (end($datavalue));
        }
        return $deductMoney * 100;
    }

    /**
     * 批量生成二维码
     */
    public function qrcode()
    {
        //定义文件位置
        // 定义文件路径
        $file_path = 'C:\Users\Administrator\Desktop\iphone.txt';
        // 检查文件是否存在并可读
        $phone_numbers = [];
        if (file_exists($file_path) && is_readable($file_path)) {
            // 用 file 函数读取文件内容，每一行会作为数组的一个元素
            $phone_numbers = file($file_path, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
            // 去除可能存在的换行符或其他空白字符
            foreach ($phone_numbers as &$number) {
                $number = trim($number);
            }
        } else {
            $this->error("文件不存在");
        }
        // 删除重复的手机号码
        $unique_phone_numbers = array_unique($phone_numbers);
//        $this->success('success', $unique_phone_numbers);
//        $data = $this->request->param();
        foreach ($unique_phone_numbers as $key => $value) {
            $data[] = User::where(['mobile' => $value])->field('id,invite_code')->find();
            foreach ($data as $key1 => $value1) {
                $info = (new quer())->yaoqingma('https://ychl.ychlkj.cn/#/?iv=' . $value1['invite_code'], $value1['invite_code']);
                 (new User())->where(['id' => $value1['id']])->update(['invite_rwm' => $info]);
            }
        }
        $this->success('success', $data);
    }

    public function setAncestors()
    {
        $data = User::where(['ancestors' => null])->field('id,pid,ancestors')->select();
        foreach ($data as $key => $value) {
            $res = User::where(['id' => $value['pid']])->find();
            if ($res['ancestors'] != null) {
                User::where(['id' => $value['id']])->update(['ancestors' => $res['ancestors'] . ',' . $res['id']]);
            }
//            User::where(['id' => $value['id']])->update(['ancestors' => $res['ancestors'] . ',' . $res['id']]);
        }
        $this->success('success', $res);
//        foreach ($data as $key => $value) {
//            User::where(['pid' => $value['id']])->update(['ancestors' => $value['ancestors'] . ',' . $value['id']]);
//            $list= User::where(['pid' => $value['id']])->select();
//            foreach ($list as $k => $v) {
//                User::where(['pid' => $v['id']])->update(['ancestors' => $v['ancestors'] . ',' . $v['id']]);
//            }
//        }
//        $this->success('success', $list);
    }

    /**
     * 发送订单通知
     *
     */
    public function sendOrderNotice()
    {
        // 定义函数：获取访问令牌
        function getAccessToken($appId, $appSecret)
        {
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$appId}&secret={$appSecret}";
            $response = file_get_contents($url);
            $data = json_decode($response, true);

            if (isset($data['access_token'])) {
                return $data['access_token'];
            } else {
                // 处理错误情况
                throw new Exception("Failed to get access token: " . $data['errmsg']);
            }
        }

        // 定义函数：推送模板消息
        function pushTemplateMessage($accessToken, $templateId, $openid, $data)
        {
            $url = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token={$accessToken}";

            $postData = array(
                'touser' => $openid,
                'template_id' => $templateId,
                'data' => $data
            );
            $options = array(
                'http' => array(
                    'header' => "Content-type: application/json",
                    'method' => 'POST',
                    'content' => json_encode($postData)
                )
            );
            $context = stream_context_create($options);
            $response = file_get_contents($url, false, $context);
            $result = json_decode($response, true);
            if ($result['errcode'] == 0) {
                echo "Template message sent successfully!";
            } else {
                // 处理错误情况
                throw new Exception("Failed to send template message: " . $result['errmsg']);
            }
        }

        // 使用示例：
        $appId = "wx513aef9f706f977f";//你的APPID
        $appSecret = "810b7d9e0343174424b6feef827bca6b";//你的APPSECRET
        $templateId = "ouZ-M2sCPr-baY35ftzrpFPUn_JWYMjXj4rFNT6uJek";//模板消息ID
        //用户的openid
        $openid = "obee76Lsqzl4Q4LysUmh9rx4G5x0";//用户的openid
        // 获取访问令牌
        $accessToken = getAccessToken($appId, $appSecret);
        $data = array(
            'time2' => array('value' => '2024-01-01', 'color' => '#173177'),//创建时间
            'phrase3' => array('value' => '你好', 'color' => '#173177'),//下单人
            'phone_number4' => array('value' => '1234567890', 'color' => '#173177'),//下单电话
            'amount6' => array('value' => '100.00', 'color' => '#173177'),//订单金额
            'character_string9' => array('value' => 'ORD123456', 'color' => '#173177')//订单电话
        );

        // 发送模板消息
        pushTemplateMessage($accessToken, $templateId, $openid, $data);
    }
}